<template>
    <div>
        <div class="search">
            <label>
                <input  v-model="keyword" class="search-input" type="text" placeholder="输入城市名或拼音" />
            </label>
        </div>
        <div class="search-content" v-show="keyword" ref="search">
           <ul>
               <li class="search-item" v-for="item of list" :key="item.id" @click="handleItemClick(item.name)">{{item.name}}</li>
               <li class="border-bottom search-item" v-if="hasNodata">没有找到匹配数据</li>
           </ul>
        </div>
    </div>
</template>

<script>
    import Bscroll from 'better-scroll'
    import {mapMutations} from 'vuex'
    export default {
        name: 'CitySearch',
        data(){
            return{
                keyword: '',
                list:[],
                timer:0,
            }
        },
        props:{
            cities:Object,
        },
        computed:{
          hasNodata(){
              return !this.list.length
          },
        },
        methods:{
            handleItemClick(name){
                this.changeCity(name);
                this.$router.push('/')
            },
            ...mapMutations(['changeCity'])
        },
        watch:{
            keyword: function () {
                if (this.timer) {
                    clearTimeout(this.timer)
                }
                if (!this.keyword) {
                    this.list = [];
                    return
                }
                this.timer = setTimeout(() => {
                    const result = [];
                    for (let i in this.cities) {
                        this.cities[i].forEach((value) => {
                            if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
                                result.push(value)
                            }
                        })
                    }
                    this.list = result
                }, 100)
            }
        },
        mounted() {
            const options={
                click:true,
                scrollX:false,
                scrollY:true,
            };
            this.scroll=new Bscroll(this.$refs.search,options)
        }
    }
</script>

<style lang="stylus" scoped>
    @import "~@/assets/Styles/varibles.styl"
    .search
        height: .72rem
        padding: 0 .1rem
        background: $bgColor
        .search-input
            box-sizing: border-box
            width: 100%
            height: .62rem
            padding: 0 .1rem
            line-height: .62rem
            text-align: center
            border-radius: .06rem
            color: #666
            touch-action :none
    .search-content
        position: absolute;
        overflow :hidden
        z-index :1
        top :1.54rem
        right:0
        left :0
        bottom :0
        .search-item
           line-height :.64rem
           padding-left :.2rem
           background :#fff
           color :#666
</style>
